import http from './interface'
import store from "@/store/index.js"


export const $http = (url, method, data, json) => {
	//设置请求前拦截器
	http.interceptor.request = (config) => {		
		// ;charset=UTF-8
		let content_type = json ? 'application/json' : "application/x-www-form-urlencoded"
		let state = store.state.appMessage;
		config.header = {
			'content-type': content_type,
			"token": "",
		}
		config.header = Object.assign(config.header, state)

		let token = uni.getStorageSync("token")
		if (token) {
			token = JSON.parse(token)
			config.header.token = token
		}
		// console.log(config)
	}


	//设置请求结束后拦截器
	http.interceptor.response = async (response) => {		
		// console.log("response.data ", response)
		let errmessage = {
			code: 404,
			data: null,
			msg: "您的网络开小差了"
		}		
		if (response.statusCode == 200 && response.data.code == 401) {
			console.log("TOKEN 过期")
			store.state.token = ""
			store.state.hasLogin = false
			store.state.userInfo = ""
			store.state.token = ""

			uni.removeStorageSync("token")
			uni.reLaunch({
				url: "/pages/user/login"
			})
		} else if (response.statusCode == undefined || response.statusCode == 500) {
			return errmessage;
		} else {
			return response.data;
		}
	}

	return http.request({
		method: method,
		url: url,
		dataType: 'json',
		data,
	})
}


function postJson(url, data) {
	return $http(url, 'POST', data)
}

function get(url, data) {
	return $http(url, 'GET', data, false)
}

function post(url, data) {
	return $http(url, 'POST', data, true)
}

function put(url, data) {
	return $http(url, 'PUT', data, true)
}

function del(url, data) {
	return $http(url, 'DELETE', data, true)
}

export default {
	postJson,
	get,
	post,
	put,
	del
}
